<template>
  <div>
    <div class="list">
      <div class="query">
        <div>
          <!-- 用户名/姓名搜索框 -->
          <el-input
            v-model="userNameValue"
            placeholder="用户名"
            prefix-icon="el-icon-search"
          ></el-input>
          <!-- 角色选择框 -->
          <el-select v-model="nameValue" placeholder="角色" class="module">
            <el-option
              v-for="item in selectRole"
              :key="item.value"
              :label="item.rname"
              :value="item.id"
            ></el-option>
          </el-select>
          <!-- 搜索按钮 -->
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchUser"
            class="module"
            >搜索</el-button
          >
          <!-- 重置按钮 -->
          <el-button
            icon="el-icon-refresh-left"
            @click="reset"
            class="module"
            style="margin: 24px 0 24px 0"
            >重置</el-button
          >
        </div>
        <div>
          <el-button
            type="primary"
            icon="el-icon-upload2"
            @click="dialogVisible = true"
            class="module"
            style="margin: 24px 10px 24px 0"
            >批量导入</el-button
          >
          <!-- 导出当前页按钮 -->
          <el-button
            type="primary"
            icon="el-icon-download"
            @click="handleExport"
            class="module"
            style="margin: 24px 24px 24px 0"
            >导出当前页</el-button
          >
        </div>
      </div>
      <el-table
        ref="multipleTable"
        :data="tableData"
        border
        :stripe="true"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <!-- 多选框 -->
        <el-table-column
          type="selection"
          align="center"
          width="55"
        ></el-table-column>
        <el-table-column label="序号" align="center">
          <template slot-scope="scope">
            {{ (pageInfo.pageNum - 1) * pageInfo.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="用户ID"
          prop="id"
          align="center"
        ></el-table-column> -->
        <el-table-column
          label="用户名"
          prop="username"
          align="center"
        ></el-table-column>
        <el-table-column
          label="真实姓名"
          prop="realname"
          align="center"
        ></el-table-column>
        <el-table-column
          label="所属角色"
          prop="rname"
          align="center"
        ></el-table-column>
        <el-table-column
          label="联系方式"
          prop="phone"
          align="center"
        ></el-table-column>
        <el-table-column label="注册时间" prop="createtime" align="center">
          <template slot-scope="scope">
            {{ scope.row.createtime.split("T")[0] }}
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="operate" align="center">
          <template slot-scope="scope">
            <el-button
              type="danger"
              size="small"
              :disabled="scope.row.rname === `管理员`"
              @click="handleDeleteUser(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="bottom">
        <div
          class="paging"
          style="display: flex; justify-content: space-between"
        >
          <el-pagination
            :current-page="pageInfo.pageNum"
            layout="total"
            :total="total"
          />
          <!-- 页数选择框 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageInfo.pageNum"
            :page-size="pageInfo.pageSize"
            layout="prev, pager, next"
            :total="total"
            :hide-on-single-page="true"
          />
        </div>
      </div>
    </div>
    <!-- 导入弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <!-- 上传组件 -->
      <el-upload
        ref="uploadRef"
        :action="uploadUrl"
        :headers="headers"
        :multiple="false"
        :show-file-list="true"
        :accept="'.xlsx'"
        :before-upload="handleBeforeUpload"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
      >
        <el-button type="primary">点击上传</el-button>
      </el-upload>
      <!-- 展示解析后的数据 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column
          v-for="(item, index) in columns"
          :key="index"
          :prop="item.prop"
          :label="item.label"
        />
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消 上 传</el-button>
        <!-- <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        > -->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { GetUser, QueryUser, DeleteUser } from "@/api/user/index.js";
import { ElMessage } from "element-ui/packages/message/index.js";
import * as XLSX from "xlsx";

export default {
  name: "sofp",
  data() {
    return {
      // 用户名/姓名搜索框
      userNameValue: "",
      // 角色选择框
      nameValue: "",
      selectRole: [
        {
          id: "管理员",
          rname: "管理员",
        },
        {
          id: "老师",
          rname: "老师",
        },
        {
          id: "学生",
          rname: "学生",
        },
      ],
      // 表格
      tableData: [],
      // 分页
      pageInfo: {
        // 当前页数
        pageNum: 1,
        // 每页显示数量
        pageSize: 9,
      },
      total: 0,
      // 当前页选中的用户ID列表
      currentPageUsers: [],
      // 控制弹窗是否显示
      dialogVisible: false,
      uploadUrl: "http://26.54.207.207:8088/back/user/excel/add",
      headers: {}, // 根据实际情况设置请求头
      uploadStatus: null, // 用于存储上传状态信息
      columns: [], // 用于存储解析后的表头数据
    };
  },
  methods: {
    // 获取用户列表
    async handleGetUser() {
      let res = await GetUser({
        pageNum: this.pageInfo.pageNum,
        pageSize: this.pageInfo.pageSize,
      });
      if (res.code === 200) {
        console.log(res.data, "asdhdassd");
        this.tableData = res.data.records;
        this.total = res.data.total;
      }
    },

    // 搜索按钮
    async searchUser() {
      let res = await QueryUser({
        pageNum: this.pageInfo.pageNum,
        pageSize: this.pageInfo.pageSize,
        username: this.userNameValue,
        rname: this.nameValue,
      });
      if (res.code === 200) {
        console.log(res, "asdhdassd");
        this.tableData = res.data.records;
        this.total = res.data.total;
      }
    },

    // 重置按钮，清空搜索条件
    reset() {
      this.userNameValue = "";
      this.nameValue = "";
      // 清空表格多选框
      this.$refs.multipleTable.clearSelection();
      this.handleGetUser();
    },
    // 导出当前页按钮
    async handleExport() {
      // 如果 currentPageUsers 为空，则默认导出当前页的所有用户
      if (this.currentPageUsers.length === 0) {
        this.currentPageUsers = this.tableData.map((user) => user.id);
      }

      // 构建导出链接
      const userIds = this.currentPageUsers.map((id) => `id=${id}`).join("&");
      const exportUrl = `/back/user/excel/export?${userIds}`;

      // 重定向到导出链接
      window.location.href = exportUrl;
    },
    // 多选框状态变化时触发
    handleSelectionChange(val) {
      this.currentPageUsers = val.map((user) => user.id);
    },

    // 删除用户
    async handleDeleteUser(row) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            let res = await DeleteUser({
              id: row.id,
            });
            if (res.code === 200) {
              console.log(row, "删除用户");
              this.$message({
                type: "success",
                message: "删除成功",
              });
              this.handleGetUser();
            } else {
              this.$message({
                type: "error",
                message: "删除失败，请稍后再试",
              });
            }
          } catch (error) {
            console.error("删除用户时发生错误:", error);
            this.$message({
              type: "error",
              message: "删除用户时发生错误",
            });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 分页数量发生变化时触发
    handleSizeChange(val) {
      this.pageInfo.pageSize = val;
      this.handleGetUser();
    },

    // 当前页发生变化时触发
    handleCurrentChange(val) {
      this.pageInfo.pageNum = val;
      this.handleGetUser();
    },
    // 弹窗关闭时触发
    handleClose() {
      this.uploadStatus = null;
      this.dialogVisible = false;
    },

    // 上传前的验证
    handleBeforeUpload(file) {
      const isXLSX =
        file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      if (!isXLSX) {
        this.$message.error("仅支持上传.xlsx文件!");
      }
      return isXLSX;
    },
    // handleBeforeUpload(file) {
    //   this.isXLSXUpload(file);
    //   const reader = new FileReader();
    //   reader.onload = (e) => {
    //     const data = e.target.result;
    //     const workbook = XLSX.read(data, { type: "binary" });
    //     const sheetName = workbook.SheetNames[0];
    //     const worksheet = workbook.Sheets[sheetName];
    //     const excelData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

    //     this.columns = excelData[0].map((item, index) => ({
    //       label: item,
    //       prop: `col${index}`,
    //     }));
    //   };
    // },
    // 上传成功处理
    handleUploadSuccess(response, file) {
      // this.$message.success("文件上传成功");
      // console.log("文件上传成功:", response);
      this.$message.success(response.msg);
      this.$refs.uploadRef.clearFiles();
      this.dialogVisible = false;
    },

    // 上传失败处理
    handleUploadError(error, file) {
      this.$message.error("文件上传失败。");
    },
  },
  mounted() {
    this.handleGetUser();
  },
};
</script>

<style scoped lang="scss">
.list {
  width: 100%;
  padding: 24px 24px 24px 24px;
}
// 查询头部
.query {
  // 用户名/姓名搜索框
  display: flex;
  justify-content: space-between;
  .el-input {
    width: 260px;
    height: 38px;
    margin: 24px 16px 25px 24px;
  }
}
</style>
